<template>
    <div>
      <Row>
        <Col span="10">
          <card class="card" icon="ios-options">
            <grid-tree-vxe-two v-if="GridTable" @getPickInfo="getPickInfo"></grid-tree-vxe-two>
          </card>
        </Col>
        <Col span="13" offset="1">
          <div>
            <h3 style="font-weight: bold">
              当前账号信息：{{severUserInfo.company_name}}
              <Button size="small" type="success" @click="updateInfo" style="margin-right: 5px" >编辑</Button>
              <Button @click="clickScope" size="small" v-if="severUserInfo.company_grade === '3' || severUserInfo.company_grade === '4'" type="primary">绘画范围</Button>
              <scope ref="scope" :severUserInfo="severUserInfo"></scope>
            </h3>
            <h3 style="font-weight: bold">当前节点：{{pickInfo.title}}</h3>
          </div>
          <div>
            <template>
              <Tabs  v-model="tabIndex" @on-click="changeTab" v-if="tabShow">
                <TabPane label="下级" name="tab1">
                  <div v-if="gradeShow">
                    <div style="margin-bottom: 20px">
                      <Col span="5"><Input style="width: 90%;" placeholder="名称" v-model="name"/></Col>
                      <Button type="info" @click="findSubordinateList"><Icon type="md-search"/>搜索</Button>
                      <Button type="info" v-if="parseInt(this.pickInfo.grade)<8" style="margin-left: 10px" @click="addLevel"><Icon type="md-add"/>添加</Button>
                    </div>
                    <template>
                      <Table border :columns="columns" :data="data">
                        <template slot-scope="{ row, index }" slot="action">
                          <Button type="primary" size="small" style="margin-right: 5px" @click="edit(row)">编辑</Button>
                          <Button v-if="parseInt(row.grade)>5" style="margin-right: 5px" type="error" size="small" @click="deleteGrid(row)">删除</Button>
                          <Button v-if="parseInt(row.grade)===6" type="success" size="small" @click="bindingGrid(row)">绑定</Button>
                        </template>
                      </Table>
                    </template>
                    <Modal
                      v-model="deleteModal"
                      title="删除操作确认"
                      @on-ok="deleteOk">
                        <h1>请确认操作，该操作会删除所创建的网格信息及其下级信息！删除数据无法恢复,请谨慎操作！</h1>
                    </Modal>
                  </div>
                  <div v-if="!gradeShow">
                    <div v-if="resultShow">
                      <Form :inline="true" :model="floorForm" :label-width="40">
                        <FormItem label="层数">
                          <Input v-model="floorForm.floorNum"></Input>
                        </FormItem>
                        <FormItem label="户数">
                          <Input v-model="floorForm.doorplateNum"></Input>
                        </FormItem>
                        <Button class="ml10" @click="createFloor" :loading="FloorButtonLoading">生成楼层</Button>
                      </Form>
                    </div>
                    <div v-if="!resultShow">
                      <div v-for="(item,index) in data" :key="index">
                        <div style="margin:5px 0px">
                              <span style="font-size: 25px">{{item.name}}F</span>
                              <Button type="info"  size="small" class="ml10" @click="updateFloor(item)">修改层名称</Button>
                              <Button type="primary" size="small" class="ml10" @click="addFloor(item,data[index+1])">插入一层</Button>
                              <Button type="error" size="small" class="ml10" @click="deleteFloor(item)">删除该层</Button>
                              <Button type="primary" size="small" class="ml10" @click="addDoorplate(item)">添加一户</Button>
                              <ButtonGroup class="ml10">
                                <Button type="info" size="small" :disabled="index===0" @click="upFloor(item,index,data)">
                                  <Icon type="ios-arrow-up"></Icon>
                                  上移
                                </Button>
                                <Button type="info" size="small" :disabled="index === data.length - 1" @click="downFloor(item,index,data)">
                                  下移
                                  <Icon type="ios-arrow-down"></Icon>
                                </Button>
                              </ButtonGroup>
                        </div>
                        <div>
                          <Row>
                            <div v-for="(item1,index1) in item.children" :key="index1">
                              <Col span="8" style="margin:5px 0px">
                                <div>
                                  <template>
                                    <div @dblclick="item1.doorplateShow=false">
                                      <Input v-if="item1.doorplateShow" style="width: 80%" readonly v-model="item1.name">
                                        <span slot="prepend">{{pickInfo.name}}-{{item.name}}-</span>
                                      </Input>
                                    </div>
                                    <div v-if="!item1.doorplateShow">
                                      <Input style="width: 80%" v-model="item1.name">
                                        <span slot="prepend">{{pickInfo.name}}-{{item.name}}-</span>
                                      </Input>
                                    </div>
                                    <div v-if="!item1.doorplateShow" style="margin-top: 10px">
                                      <ButtonGroup>
                                        <Button class="buttonGroupB" @click="updateDoorplate(item1)">
                                          <Icon type="md-checkmark"></Icon>
                                        </Button>
                                        <Button class="buttonGroupB" @click="item1.doorplateShow=true">
                                          <Icon type="md-close"></Icon>
                                        </Button>
                                        <Button class="buttonGroupB" @click="deleteDoorplate(item1)">
                                          <Icon type="md-trash"></Icon>
                                        </Button>
                                      </ButtonGroup>
                                    </div>
                                  </template>
                                </div>
                              </Col>
                            </div>
                          </Row>
                        </div>
                      </div>
                    </div>
                  </div>
                </TabPane>
                <TabPane label="场所" name="tab2" v-if="pickInfo.grade==='6'">
                    <merchant ref="child" :pickInfo="pickInfo"></merchant>
                </TabPane>
                <TabPane label="社会组织" name="tab3" v-if="pickInfo.grade==='6'">
                  <society ref="society" :pickInfo="pickInfo"></society>
                </TabPane>
                <TabPane label="物件" name="tab4" v-if="pickInfo.grade==='6'">
                  <substance ref="substance" :pickInfo="pickInfo"></substance>
                </TabPane>
               `<TabPane label="添加管理人员" name="tab5" v-if="parseInt(this.pickInfo.grade)>=5 && parseInt(this.pickInfo.grade)<=7">
                  <manager ref="manager" :pickInfo="pickInfo"></manager>
                </TabPane>
              </Tabs>
            </template>
          </div>
        </Col>
      </Row>
      <scope :severUserInfo="severUserInfo"></scope>
      <Modal v-model="modal1" title="网格基本信息" width="500" cancel-text="关闭" @on-ok="pickOk"
              @on-cancel="modal1=false" ok-text="确定">
        <Form :model="paramData">
          <Row style="margin-bottom: 10px">
            <Col span="5" style="text-align: right;line-height: 35px">名称:</Col>
            <Col span="13" offset="1">
              <Input v-model="paramData.name"></Input>
            </Col>
          </Row>
          <Row v-if="parseInt(this.pickInfo.grade)===6" style="margin-bottom: 10px">
            <Col span="5" style="text-align: right;line-height: 35px">蓝牌号:</Col>
            <Col span="13" offset="1">
              <Input v-model="paramData.brand"></Input>
            </Col>
          </Row>
          <Row v-if="parseInt(this.pickInfo.grade)<7">
            <Col span="5" style="text-align: right;line-height: 35px">坐标:</Col>
            <Col span="9" offset="1">
              <Input v-model="paramData.csc_mapjson" disabled></Input>
            </Col>
            <Col span="5" offset="1">
              <Button @click="pickMap">选择</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal v-model="modalMap" fullscreen title="地图选点" @on-ok="modalMapOk()">
        <div class="amap-page-container" v-if="msg">
<!--     地图边框  搜索框     -->
          <el-amap-search-box v-if="this.pickInfo.grade<=4" class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
<!--     地图     -->
          <el-amap vid="amap" class="amap-demo" :zoom="zoom" :center="center" :events="events">
<!--     地图标记     -->
            <el-amap-marker vid="index_center" :position="center"></el-amap-marker>
            <el-amap-polygon v-for="(polygon, index2) in GridScope" :key="index2" :vid="polygon"
                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                             :fillOpacity="polygon.fillOpacity"></el-amap-polygon>
          </el-amap>
        </div>
        <div class="toolbar">
          <h2>当前选中坐标: [{{ lng }}, {{ lat }}] <span v-if="this.address!=''">地址:</span> {{ address }}</h2>
        </div>
      </Modal>
      <Modal v-model="modalMap2" fullscreen title="小组区域选择" @on-ok="modalMap2Ok()">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amap2" class="amap-demo" :zoom="zoom" :center="center">
            <el-amap-marker vid="index_center" :position="center"></el-amap-marker>
            <el-amap-polygon v-for="(polygon, index) in polygons" :key="index" :vid="polygon"
                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                             :fillOpacity="polygon.fillOpacity" :editable="polygon.editable"></el-amap-polygon>
            <el-amap-polygon v-for="(polygon, index2) in polygonsList" :key="index2" :vid="polygon"
                             :path="polygon.path" :fillColor="polygon.fillColor" :bubble="polygon.bubble"
                             :fillOpacity="polygon.fillOpacity"></el-amap-polygon>
          </el-amap>
        </div>
      </Modal>
      <Modal v-model="FloorModal" title="楼层信息" @on-ok="FloorOK">
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">名称:</Col>
          <Col span="13" offset="1">
            <Input v-model="FloorInfo.name">
              <span slot="append">F</span>
            </Input>
          </Col>
        </Row>
      </Modal>
      <Modal v-model="DoorplateModal" title="户信息" @on-ok="DoorplateOk">
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">名称:</Col>
          <Col span="13" offset="1">
            <Input v-model="DoorplateInfo.name">
              <span slot="append">F</span>
            </Input>
          </Col>
        </Row>
      </Modal>
      <Modal
        width="1200"
        v-model="GridModal"
        title="绑定小区名称">
        <template>
          <Tabs :value="GridTab" @on-click="tabClick">
            <TabPane label="当前绑定" name="1">
              <template>
                <Table border :columns="YBDColumns" :data="YBDData">
                  <template slot-scope="{ row }" slot="type">
                    <strong v-if="row.type==='0'">老小区</strong>
                    <strong v-if="row.type==='1'">新小区</strong>
                  </template>
                  <template slot-scope="{ row, index }" slot="action">
                    <Button type="primary" size="small" style="margin-right: 5px" @click="GridBinding(2,row.id)">解除绑定</Button>
                  </template>
                </Table>
              </template>
            </TabPane>
            <TabPane label="绑定" name="0">
              <div style="margin-bottom: 20px">
                <Select placeholder="请选择小区类型" v-model="xqParams.type" style="width:165px;margin-right: 10px">
                  <Option value="" >全部</Option>
                  <Option value="0" >老小区</Option>
                  <Option value="1" >新小区</Option>
                </Select>
                <template>
                  <Input v-model="xqParams.residence_name" placeholder="请输入小区名称" style="width: 165px;margin-right: 10px" />
                </template>
                <Button type="primary"  style="margin-right: 5px" @click="selectList">搜索</Button>
              </div>
              <template>
                <Table border :columns="WBDColumns" :data="WBDData">
                  <template slot-scope="{ row }" slot="type">
                    <strong v-if="row.type==='0'">老小区</strong>
                    <strong v-if="row.type==='1'">新小区</strong>
                  </template>
                  <template slot-scope="{ row, index }" slot="action">
                    <Button type="primary" size="small" style="margin-right: 5px"  @click="GridBinding(1,row.id)">绑定</Button>
                  </template>
                </Table>
              </template>
              <Page style="text-align: right;margin-top: 20px" :current="xqParams.pageNo" :total="xqParams.totalRecord" show-sizer :page-size="xqParams.pageSize" show-elevator
                    @on-change="pageAction" @on-page-size-change="pageSizeChange"/>
            </TabPane>
          </Tabs>
        </template>
      </Modal>
    </div>
</template>

<script>
import {
  updateFloorSort,
  findOfficeLevelList,
  findSubordinateList,
  insertCoordinate,
  createFloor,
  updateDoorplate,
  updateFloor,
  createFloorDoorplate,
  findXQList, findBindingList, updateBinding
} from '@/api/eventlist'
import Merchant from './components/merchant'
import GridTreeVxeTwo from './components/grid-tree-vxe-two'
import Society from './components/society'
import Substance from './components/substance'
import Manager from './components/manager'
import { deleteGridInfo, disposeGridScope, findGridGardenList } from '../../../api/eventlist'
import Scope from './components/scope'

export default {
  name: 'index',
  components: { Scope, Manager, Substance, Society, GridTreeVxeTwo, Merchant },
  data () {
    let self = this
    return {
      GridScope: [],
      WBDColumns: [
        {
          title: '区域',
          key: 'area'
        },
        {
          title: '小区名称',
          key: 'residence_name'
        },
        {
          title: '小区类型',
          slot: 'type'
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ],
      WBDData: [],
      YBDColumns: [
        {
          title: '小区名称',
          key: 'residence_name'
        },
        {
          title: '小区类型',
          slot: 'type'
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ],
      YBDData: [],
      GridTab: '0',
      GridModal: false,
      FloorButtonLoading: false,
      GridTable: true,
      deleteModal: false,
      deleteRow: {},
      tabShow: true,
      firstInfo: {},
      severUserInfo: {},
      sort: 0,
      floorForm: {},
      show: true,
      gradeShow: true,
      resultShow: true,
      FloorModal: false,
      DoorplateModal: false,
      name: '',
      tabIndex: 0,
      parentList: [],
      datalist: [],
      paramData: {},
      // 网格基本信息
      modal1: false,
      pickInfo: {},
      FloorInfo: {},
      DoorplateInfo: {},
      columns: [
        {
          title: '名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      data: [],
      modalMap: false,
      modalMap2: false,
      zoom: 9, // 缩放
      address: '',
      lng: 0,
      lat: 0,
      center: [123.4650090000, 41.6772870000],
      searchOption: {
        city: '沈阳',
        citylimit: true
      },
      msg: true,
      polygons: [
        {
          bubble: true,
          editable: true,
          fillOpacity: '0.2',
          fillColor: '#f77777',
          path: []
        }
      ],
      selectVal: '',
      events: {
        click (e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
          self.center = [lng, lat]
        }
      },
      polygonsList: [],
      BDmodalData: {},
      xqParams: {
        residence_name: '',
        type: '',
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      }
    }
  },
  methods: {
    clickScope () {
      this.$refs.scope.init()
    },
    // 绑定
    bindingGrid (e) {
      this.GridModal = true
      this.BDmodalData = e
      this.GridTab = '0'
      this.findXQList()
    },
    pageAction (page) {
      this.xqParams.pageNo = page
      this.findXQList()
    },
    pageSizeChange (e) {
      this.xqParams.pageSize = e
      this.findXQList(this.xqParams.pageNo)
    },
    selectList () {
      this.xqParams.pageNo = 1
      this.findXQList()
    },
    findXQList () {
      let data = this.xqParams
      findXQList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.WBDData = ret.data.data.results
          this.xqParams.totalRecord = ret.data.data.totalRecord
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    findBindingList () {
      let data = {
        id: this.BDmodalData.id
      }
      findBindingList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.YBDData = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    tabClick (e) {
      if (e === '0') {
        this.findXQList()
      } else if (e === '1') {
        this.findBindingList()
      }
    },
    GridBinding (e1, e2) {
      let data = {
        type: e1,
        czType: e1,
        binding: e2,
        id: this.BDmodalData.id
      }
      updateBinding(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '操作成功', desc: ret.data.errmsg })
          if (e1 === 1) {
            this.findBindingList()
            this.GridTab = '1'
          } else if (e1 === 2) {
            this.findBindingList()
          }
        } else {
          this.$Notice.error({ title: '操作失败', desc: ret.data.errmsg })
        }
      })
    },
    // 删除确认
    deleteGrid (e) {
      this.deleteModal = true
      this.deleteRow = e
    },
    // 删除网格
    deleteOk () {
      let data = {
        id: this.deleteRow.id,
        grade: this.deleteRow.grade
      }
      deleteGridInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '删除成功', desc: ret.data.errmsg })
          this.GridTable = false
          this.$nextTick(() => {
            this.GridTable = true
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({ title: '删除失败', desc: ret.data.errmsg })
        }
      })
    },
    updateInfo () {
      findOfficeLevelList().then(ret => {
        if (ret.data.errcode === 0) {
          this.pickInfo = this.firstInfo
          this.paramData = {}
          this.modal1 = true
          this.paramData = ret.data.data
        } else {
          this.$Notice.error({
            title: '查询失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 编辑中心点
    edit (val) {
      this.paramData = {}
      this.modal1 = true
      this.paramData = val
    },
    // 获取当前级别信息
    getPickInfo (e1) {
      this.tabShow = false
      this.$nextTick(() => {
        this.tabShow = true
        this.tabIndex = 0
      })
      if (e1.grade === '5' || e1.grade === '4' || e1.grade === '3') {
        this.firstInfo = e1
      }
      this.pickInfo = e1
      this.findSubordinateList()
      if (this.pickInfo.grade === '6') {
        let that = this
        setTimeout(function () {
          that.$refs.child.init()
          that.$refs.society.init()
          that.$refs.substance.init()
          that.$refs.manager.init()
        }, 1000)
      }
    },
    // 切换tab
    changeTab (e) {
      if (e === 'tab1') {
        this.findSubordinateList()
      } else if (e === 'tab2') {
        this.$refs.child.init()
      } else if (e === 'tab3') {
        this.$refs.society.init()
      } else if (e === 'tab4') {
        this.$refs.substance.init()
      } else if (e === 'tab5') {
        this.$refs.manager.init()
      }
    },
    // 层（上移）
    upFloor (e, e1, e2) {
      let data = {
        id1: e.id, // 本行
        id2: e2[e1 - 1].id// 上一行id
      }
      updateFloorSort(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '修改成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '修改失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 层（下移）
    downFloor (e, e1, e2) {
      let data = {
        id1: e.id, // 本行
        id2: e2[e1 + 1].id// 下一行id
      }
      updateFloorSort(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '修改成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '修改失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 批量生成楼层，户
    createFloor () {
      this.FloorButtonLoading = true
      let data = {
        floorNum: this.floorForm.floorNum,
        doorplateNum: this.floorForm.doorplateNum,
        unit_id: this.pickInfo.id
      }
      createFloor(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '创建成功',
            desc: ret.data.errmsg
          })
          this.FloorButtonLoading = false
          this.floorForm.floorNum = ''
          this.floorForm.doorplateNum = ''
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '创建失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 添加层 弹窗
    addFloor (e, e1) {
      this.sort = 0
      this.FloorInfo = {}
      if (e1 === undefined) {
        this.sort = e.sort + 10000
      } else {
        this.sort = (e.sort + e1.sort) / 2
      }
      this.FloorModal = true
    },
    // 修改层 弹窗
    updateFloor (e) {
      this.FloorModal = true
      this.FloorInfo = e
    },
    // 添加户 弹窗
    addDoorplate (e) {
      this.DoorplateInfo = {}
      this.DoorplateModal = true
      this.FloorInfo = e
    },
    // 新增户确定
    DoorplateOk () {
      console.log(1231213)
      let data = {}
      if (this.FloorInfo.children.length === 0) {
        data = {
          floor_id: this.FloorInfo.id, // 层id
          name: this.DoorplateInfo.name,
          type: 'doorplate',
          sort: 100,
          grade: '10'
        }
        console.log(123)
      } else {
        data = {
          floor_id: this.FloorInfo.id, // 层id
          name: this.DoorplateInfo.name,
          type: 'doorplate',
          sort: this.FloorInfo.children[this.FloorInfo.children.length - 1].sort + 100,
          grade: '10'
        }
        console.log(456)
      }

      this.createFloorDoorplate(data)
    },
    // 新增，修改层确定
    FloorOK () {
      if (this.FloorInfo.id === undefined) {
        // 新增
        let data = {
          unit_id: this.pickInfo.id, // 上级id
          name: this.FloorInfo.name,
          type: 'floor',
          sort: this.sort,
          grade: '9'
        }
        this.createFloorDoorplate(data)
      } else {
        // 修改
        let data = {
          id: this.FloorInfo.id,
          name: this.FloorInfo.name,
          sort: this.FloorInfo.sort
        }
        updateFloor(data).then(ret => {
          if (ret.data.errcode === 0) {
            this.$Notice.success({
              title: '修改成功',
              desc: ret.data.errmsg
            })
            this.findSubordinateList()
          } else {
            this.$Notice.error({
              title: '修改失败',
              desc: ret.data.errmsg
            })
          }
        })
      }
    },
    // 单独添加层户，接口调用
    createFloorDoorplate (e) {
      createFloorDoorplate(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 修改户
    updateDoorplate (e) {
      let data = {
        id: e.id,
        name: e.name,
        sort: e.sort
      }
      updateDoorplate(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '修改成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '修改失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 删除层
    deleteFloor (e) {
      let data = {
        id: e.id,
        grade: e.grade
      }
      deleteGridInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '删除成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '删除失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 删除户
    deleteDoorplate (e) {
      let data = {
        id: e.id,
        grade: e.grade
      }
      deleteGridInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({
            title: '修改成功',
            desc: ret.data.errmsg
          })
          this.findSubordinateList()
        } else {
          this.$Notice.error({
            title: '修改失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 查询下级，供列表展示
    findSubordinateList () {
      let data = {
        id: this.pickInfo.id,
        name: this.name,
        grade: this.pickInfo.grade
      }
      findSubordinateList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.data = ret.data.data
          if (this.pickInfo.grade === '8') {
            this.gradeShow = false
            if (this.data.length > 0) {
              this.resultShow = false
            } else {
              this.resultShow = true
            }
          } else {
            this.gradeShow = true
          }
        } else {
          this.$Notice.error({
            title: '获取下级列表失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 地图选点
    pickMap () {
      if (this.paramData.grade === '6' || (this.paramData.grade === undefined && this.pickInfo.grade === '5')) {
        console.log(789789789)
        this.polygonsList = []
        this.findGridGardenList()
        // 画格
        if (this.paramData.csc_mapjson !== undefined && this.paramData.csc_mapjson !== '') {
          // 有信息
          this.polygons[0].path = JSON.parse(this.paramData.csc_mapjson)
          this.center = []
          this.center = this.polygons[0].path[0]
          this.autoZoom(this.pickInfo)
          this.modalMap2 = true
        } else {
          // 无信息
          // 上一级同样无选点信息
          if (this.pickInfo.csc_mapjson === null || this.pickInfo.csc_mapjson === undefined || this.pickInfo.csc_mapjson === '') {
            this.$Notice.error({
              title: '选点失败',
              desc: '请为社区选点，否则无法绘画网格'
            })
          } else {
            this.center = []
            let x = this.pickInfo.csc_mapjson.split(',')
            this.center.push(x[0])
            this.center.push(x[1])
            this.autoZoom(this.pickInfo)
            this.modalMap2 = true
            this.autoPolygon()
          }
        }
      } else {
        // 选点
        if (this.paramData.csc_mapjson !== undefined && this.paramData.csc_mapjson !== '') {
          // 有信息
          this.center = []
          let x = this.paramData.csc_mapjson.split(',')
          this.center.push(x[0])
          this.center.push(x[1])
          this.lng = x[0]
          this.lat = x[1]
          this.autoZoom(this.paramData)
          this.modalMap = true
        } else {
          // 无信息
          if (this.pickInfo.csc_mapjson === null || this.pickInfo.csc_mapjson === undefined || this.pickInfo.csc_mapjson === '') {
            // 上一级同样无选点信息
            this.modalMap = true
          } else {
            this.center = []
            if (this.pickInfo.grade === '6') {
              // 根据四边形坐标获取中心点
              console.log(123123)
              this.center = this.autoCenter(this.pickInfo.csc_mapjson)
              this.disposeBuildingGrid(this.pickInfo.csc_mapjson)
            } else {
              console.log(4545645)
              let x = this.pickInfo.csc_mapjson.split(',')
              this.center.push(x[0])
              this.center.push(x[1])
              this.lng = x[0]
              this.lat = x[1]
            }
            this.autoZoom(this.pickInfo)
            this.modalMap = true
          }
        }
      }
    },
    // 调整缩放程度
    autoZoom (e) {
      if (parseInt(e.grade) === 7) {
        this.zoom = 17 // 小组
      } else if (parseInt(e.grade) === 6) {
        this.zoom = 16 // 小区
      } else if (parseInt(e.grade) === 5) {
        this.zoom = 15 // 社区
      } else if (parseInt(e.grade) === 4) {
        this.zoom = 14 // 街道
      } else if (parseInt(e.grade) === 3) {
        this.zoom = 13 // 区
      }
    },
    // 地图搜索x框
    onSearchResult (pois) {
      if (pois.length > 0) {
        this.zoom = 14
        this.center = [pois[0].lng, pois[0].lat]
        this.lng = pois[0].lng
        this.lat = pois[0].lat
      }
    },
    // 选点地图确认
    modalMapOk () {
      this.paramData.csc_mapjson = this.lng + ',' + this.lat
    },
    // 画格地图确认
    modalMap2Ok () {
      if (this.polygons[0].path.length) {
        this.paramData.csc_mapjson = []
        let newpath = []
        this.polygons[0].path.forEach(item => {
          let lng = item.lng
          let lat = item.lat
          let point = [lng, lat]
          newpath.push(point)
        })
        this.paramData.csc_mapjson = JSON.stringify(newpath)
        this.GridVerify()
      } else {
        this.$Notice.error({
          title: '选择失败',
          desc: '区域选择失败'
        })
      }
    },
    // 网格校验
    GridVerify () {
      let data = this.paramData
      disposeGridScope(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.modalMap2 = false
        } else {
          this.$Notice.error({
            title: '选择失败',
            desc: ret.data.errmsg
          })
          this.modalMap2 = true
        }
      })
    },
    // 选点保存
    pickOk () {
      if (this.pickInfo.grade === '2' || this.pickInfo.grade === '3' || this.pickInfo.grade === '4' || (this.pickInfo.grade === '5' && this.paramData.grade === '5')) {
        // 操作的是 市（2） 区（3），街道（4），社区（5）
        let data = {}
        if (this.lng === 0 || this.lat === 0 || this.lng === '' || this.lat === '') {
          console.log(123)
          data = {
            id: this.paramData.id,
            csc_mapjson: this.paramData.csc_mapjson,
            grade: this.paramData.grade
          }
        } else {
          console.log(456)
          data = {
            id: this.paramData.id,
            csc_mapjson: this.lng + ',' + this.lat,
            grade: this.paramData.grade
          }
        }
        this.insertCoordinate(data)
      } else if (this.pickInfo.grade === '5' && this.paramData.grade !== '5') {
        if (this.paramData.id === undefined) {
          // 新增
          let data = {
            name: this.paramData.name,
            parent_ids: this.pickInfo.parent_ids,
            csc_mapjson: this.paramData.csc_mapjson,
            grade: '6',
            community: this.pickInfo.name,
            community_id: this.pickInfo.id,
            company_code: this.pickInfo.code
          }
          this.insertCoordinate(data)
        } else {
          // 修改
          let data = {
            grade: '6',
            name: this.paramData.name,
            csc_mapjson: this.paramData.csc_mapjson,
            id: this.paramData.id
          }
          this.insertCoordinate(data)
        }
      } else if (this.pickInfo.grade === '6') {
        if (this.paramData.id === undefined) {
        // 新增
          let data = {
            name: this.paramData.name,
            csc_mapjson: this.paramData.csc_mapjson,
            grade: '7',
            garden_id: this.pickInfo.id,
            company_code: this.pickInfo.company_code,
            brand: this.paramData.brand
          }
          this.insertCoordinate(data)
        } else {
        // 修改
          let data = {
            name: this.paramData.name,
            csc_mapjson: this.paramData.csc_mapjson,
            grade: '7',
            garden_id: this.pickInfo.id,
            id: this.paramData.id,
            brand: this.paramData.brand
          }
          this.insertCoordinate(data)
        }
      } else if (this.pickInfo.grade === '7') {
        if (this.paramData.id === undefined) {
          let data = {
            name: this.paramData.name,
            grade: '8',
            building_id: this.pickInfo.id,
            company_code: this.pickInfo.company_code
          }
          this.insertCoordinate(data)
        } else {
          let data = {
            name: this.paramData.name,
            grade: '8',
            building_id: this.pickInfo.id,
            id: this.paramData.id
          }
          this.insertCoordinate(data)
        }
      }
    },
    // 保存接口
    insertCoordinate (e) {
      insertCoordinate(e).then(ret => {
        if (ret.data.errcode === 0) {
          this.modal1 = false
          this.msg = false
          this.$nextTick(() => {
            this.msg = true
          })
          if (e.grade === '5') {
            this.GridTable = false
            this.$nextTick(() => {
              this.GridTable = true
            })
          }
          this.lng = ''
          this.lat = ''
          this.$Notice.success({
            title: '保存成功！',
            desc: ret.data.errmsg
          })
        } else {
          this.$Notice.error({
            title: '保存失败！',
            desc: ret.data.errmsg
          })
        }
      })
    },
    // 添加下级
    addLevel () {
      if (this.pickInfo.grade === '2' || this.pickInfo.grade === '3' || this.pickInfo.grade === '4') {
        this.$Notice.error({
          title: '添加失败',
          desc: '此级别禁止添加'
        })
      } else {
        this.paramData = {}
        this.modal1 = true
      }
    },
    // 根据多边形自动取中心点
    autoCenter (map) {
      let path = JSON.parse(map)
      let total_lng = 0.0
      let total_lat = 0.0
      path.forEach(arr => {
        total_lng += arr[0]
        total_lat += arr[1]
      })
      let newlng = total_lng / path.length
      let newlat = total_lat / path.length
      let newCenter = [newlng, newlat]
      return newCenter
    },
    // 根据当前中心点自动生成一组四边形坐标
    autoPolygon () {
      let lng = parseFloat(this.center[0])
      let lat = parseFloat(this.center[1])
      let center = [lng, lat]
      let lng1 = lng + 0.002
      let lat1 = lat
      let center1 = [lng1, lat1]
      let lng2 = lng + 0.002
      let lat2 = lat + 0.002
      let center2 = [lng2, lat2]
      let lng3 = lng
      let lat3 = lat + 0.002
      let center3 = [lng3, lat3]
      this.polygons[0].path = []
      this.polygons[0].path.push(center)
      this.polygons[0].path.push(center1)
      this.polygons[0].path.push(center2)
      this.polygons[0].path.push(center3)
    },
    // 处理多边形
    dispose (e) {
      try {
        let data = {
          bubble: true,
          fillColor: '#f77777',
          fillOpacity: '0.2',
          path: JSON.parse(e)
        }
        this.polygonsList.push(data)
        // this.polygons[0].path.push()
      } catch (e) {
        this.$Notice.error({
          title: '获取失败',
          desc: '数据格式不正确，重新选择'
        })
      }
    },
    disposeBuildingGrid (e) {
      try {
        let data = {
          bubble: true,
          fillColor: '#f77777',
          fillOpacity: '0.2',
          path: JSON.parse(e)
        }
        this.GridScope.push(data)
        // this.polygons[0].path.push()
      } catch (e) {
        this.$Notice.error({
          title: '获取失败',
          desc: '数据格式不正确，重新选择'
        })
      }
    },
    // 查询社区下网格
    findGridGardenList () {
      findGridGardenList().then(ret => {
        if (ret.data.errcode === 0) {
          if (ret.data.data.length > 0) {
            let result = ret.data.data
            result.forEach(item => {
              this.dispose(item.csc_mapjson)
            })
          }
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.msg })
        }
      })
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
  }
}
</script>

<style scoped>
  .card>>>.ivu-card-body{
    padding: 0;
  }
  .amap-demo {
    height: 600px;
  }
  /*// 表格滚动条*/
     .ivu-table-overflowX {
       overflow-x: hidden;
     }

  /*// 模态框*/
     .item1 {
       height: 42px;
       line-height: 40px;
     }

  /*// 地图*/
     .amap-page-container {
       position: relative;
       width: 100%;
       height: 88%;
     }

  /*// 地图选点预览工具栏*/
     .toolbar {
       display: block;
       text-align: center;
       height: 20px;
       margin-top: 50px;
     }
  .ml10 {
    margin-left: 10px;
  }

  .buttonGroupB{
    margin-right: 5px;
  }

  .hu_input {
    width: 40px;
    margin-right: 5px;
  }
</style>
